package cn.xd.base.application.service.command.impl;

import cn.xd.base.application.assembler.AdminMenuAssembler;
import cn.xd.base.application.service.command.AdminMenuAppService;
import cn.xd.base.basic.type.AdminMenuId;
import cn.xd.base.domain.bean.command.AddAdminMenuCommand;
import cn.xd.base.domain.bean.command.UpdateAdminMenuCommand;
import cn.xd.base.domain.bean.response.AdminMenuDTO;
import cn.xd.base.domain.entity.AdminMenu;
import cn.xd.base.domain.repository.AdminMenuRepository;
import cn.xd.base.persistence.dos.AdminRoleMenuDO;
import cn.xd.base.persistence.mps.AdminRoleMenuMpService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminMenuAppServiceImpl implements AdminMenuAppService {

    @Resource
    private AdminMenuRepository adminMenuRepository;
    @Resource
    private AdminRoleMenuMpService adminRoleMenuMpService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminMenuDTO updateAdminMenu(UpdateAdminMenuCommand command, Long userId) {
        AdminMenu adminMenu = adminMenuRepository.find(AdminMenuId.of(command.getId())).isEmptyThrow("菜单不存在");
        adminMenu.update(command, userId);
        adminMenuRepository.save(adminMenu);
        return AdminMenuAssembler.INSTANCE.toDTO(adminMenu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdminMenuDTO addAdminMenu(AddAdminMenuCommand command, Long userId) {
        AdminMenu add = AdminMenu.add(command, userId);
        adminMenuRepository.save(add);
        return AdminMenuAssembler.INSTANCE.toDTO(add);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAdminMenu(Long id) {
        AdminMenu adminMenu = adminMenuRepository.find(AdminMenuId.of(id)).isEmptyThrow("菜单不存在");
        adminRoleMenuMpService.remove(new LambdaQueryWrapper<AdminRoleMenuDO>().eq(AdminRoleMenuDO::getMenuId, id));
        adminMenuRepository.remove(adminMenu);
    }
}

